package leecode.一元一次;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OneValueSolution {
    public static void main(String[] args) {
        System.out.println("*************");
        String s = "x-1-x=0";
        solve(s);
        System.out.println("*************");
    }

    private static void solve(String s) {
        String[] split = s.split("=");
        String left = split[0];
        Map<StringBuilder, Character> map = creatMap(left);
        double x = calX(map);
        System.out.println(x);
    }

    private static double calX(Map<StringBuilder, Character> map) {
        List<Integer> xValue = new ArrayList<>();
        List<Integer> num = new ArrayList<>();
        for (Map.Entry<StringBuilder, Character> entry : map.entrySet()) {
//            String s = "301x-1-2x+100-1002=3";
            if (entry.getKey().toString().endsWith("x")) {
                String va = entry.getKey().toString().replace("x", "");
                if ("".equals(va)) {
                    va = "1";
                }
                if (entry.getValue() == '+') {
                    xValue.add(Integer.parseInt(va));
                } else {
                    Integer integer = -Integer.parseInt(va);
                    xValue.add(integer);
                }
            } else {
                String va = entry.getKey().toString();
                if (entry.getValue() == '+') {
                    num.add(Integer.parseInt(va));
                } else {
                    Integer integer = -Integer.parseInt(va);
                    num.add(integer);
                }
            }
        }
        double sumX = 0;
        double sumVal = 0;
        for (Integer integer : xValue) {
            sumX += integer;
        }
        for (Integer integer : num) {
            sumVal += integer;
        }
        if (sumX - 0 < 1E-6) {
            return -0.001;
        } else {
            return -sumVal / sumX;
        }
    }

    private static Map<StringBuilder, Character> creatMap(String left) {
        char[] charLeft = left.toCharArray();
        StringBuilder sb = new StringBuilder();
        char sym = '+';
        Map<StringBuilder, Character> map = new HashMap<>();
        for (int i = 0; i < charLeft.length; i++) {
            char c = charLeft[i];
            if (i == 0) {
                sym = '+';
            }
            if (c >= '0' && c <= '9' || (c == 'x' || c == 'X')) {
                sb.append(c);
                continue;
            }
            if (c == '+' || c == '-') {
                StringBuilder newSb = new StringBuilder(sb);
                Character newSym = sym;
                map.put(newSb, newSym);
                sb.delete(0, sb.length());
                sym = c;
            }
        }
        map.put(sb, sym);
        return map;
    }
}
